library yggy;

uses
  SysUtils,
  Windows,
  Winsock,
  Hook in 'Functions\Hook.pas',
  Misc in 'Functions\Misc.pas',
  Messenger in 'Functions\Messenger.pas',
  DirectDraw in 'Headers\DirectDraw.pas',
  DXCommon in 'Headers\DXCommon.pas';

{$R *.RES}

{$E dll}

var
  recvNextHook: function(s: TSocket; buf : Pointer; len, flags: Integer): Integer; stdcall;
  sendNextHook: function(s: TSocket; var buf; len, flags: Integer): Integer; stdcall;

const
  szTargetExe    : string = 'ideal.exe';
  ipcStartString : string = 'nil';

function recvHookProc(s: TSocket; buf : Pointer; len, flags: Integer): Integer; stdcall;
begin
  Echo(ConvertDataToHex(buf, len));
  //call the real winsock function
  Result := recvNextHook(s, buf, len, flags);
end;

function sendHookProc(s: TSocket; var buf; len, flags: Integer): Integer; stdcall;
begin
  Echo(ConvertDataToHex(@buf, len));
  //call the real winsock function
  Result := sendNextHook(s, buf, len, flags);
end;

procedure EntryPoint(Reason: dword);
begin
  if Reason = DLL_PROCESS_ATTACH then
  begin
    if LowerCase(ExtractFileName(ParamStr(0))) = szTargetExe then
    begin
      //Create file mapping
      CreateMap();
      //Hook winsock send/recv
      HookCode(GetProcAddress(GetModuleHandle('ws2_32.dll'), 'recv'),
               @recvHookProc, @recvNextHook);
      HookCode(GetProcAddress(GetModuleHandle('ws2_32.dll'), 'send'),
               @sendHookProc, @sendNextHook);
      //Trigger IPC initialization on launcher
      Echo(ipcStartString);
    end;
  end;
end;

begin
  DLLProc := @EntryPoint;
  EntryPoint(DLL_PROCESS_ATTACH);
end.
